package com.fs.aliyun.mns;

import com.alibaba.fastjson.JSON;
import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.CloudQueue;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.common.ClientException;
import com.aliyun.mns.common.ServiceException;
import com.aliyun.mns.model.Message;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.Date;
import java.util.List;
import java.util.Map;

public class ProducerDemo {

	private MNSClient client;

	@Before
	public void setUp() {
		CloudAccount account = new CloudAccount("LTAId52CQ6kbSGlU", "rtfbvsLFpHIEV4Xi23Licpuz7ONVX3", "https://1370344375688957.mns.cn-beijing.aliyuncs.com/");
		client = account.getMNSClient(); // 在程序中，CloudAccount以及MNSClient单例实现即可，多线程安全
	}

	@Test
	public void testSendToTopic() {
		CloudQueue queue = client.getQueueRef("dev-car-raffle");
		try {
			Message message = new Message();
			message.setMessageBody("{\"carId\":940,\"cityStcode\":440600,\"date\":1504253147181,\"storeId\":10000004,\"uid\":10358,\"vinCode\":\"LSGPC52H1F9579157\"}", Message.MessageBodyType.RAW_STRING);
			queue.putMessage(message);
			System.out.println(message.getMessageId());
			System.out.println(message.getMessageBodyMD5());
			System.out.println(message.getMessageBody());
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("subscribe error");
		}

	}

	@Test
	public void testSendNormal() {
		EmailDto emailDto = new EmailDto();
		emailDto.setReceivers(new String[] { "fangshuai0119@163.com" });
		emailDto.setSubject("这是一个测试主题");
		emailDto.setContent("这是一段测试内容");
		emailDto.setCallerId(1L);

		sendMessage(JSON.toJSONString(emailDto));
	}

	@Test
	public void testSendAttachment() {
		EmailDto emailDto = new EmailDto();
		emailDto.setReceivers(new String[] { "fangshuai0119@163.com" });
		emailDto.setSubject("这是一个测试主题");
		emailDto.setContent("这是一段测试内容");
		emailDto.setCallerId(1L);
		emailDto.setAttachmentId(new Long[] { 1L });

		sendMessage(JSON.toJSONString(emailDto));
	}

	@Test
	public void testSendText() {
		EmailDto emailDto = new EmailDto();
		emailDto.setReceivers(new String[] { "fangshuai0119@163.com" });
		emailDto.setSubject("这是一个测试主题");
		emailDto.setCallerId(1L);
		emailDto.setTemplateId(1L);

		sendMessage(JSON.toJSONString(emailDto));
	}

	@Test
	public void testSendHtml() {
		EmailDto emailDto = new EmailDto();
		emailDto.setReceivers(new String[] { "fangshuai0119@163.com" });
		emailDto.setSubject("这是一个测试主题");
		emailDto.setCallerId(1L);
		emailDto.setTemplateId(2L);
		emailDto.setCc(new String[] { "qi.che03@163.com", "fangshuai@163.com" });
		emailDto.setBcc(new String[] { "shuai.fang@163.com", "shuai@163.com" });
		emailDto.setAttachmentId(new Long[] {1L, 3L});
		emailDto.setContent("内容主体");

		System.out.println(JSON.toJSONString(emailDto));

		sendMessage(JSON.toJSONString(emailDto));
	}

	@Test
	public void testSendVelocity() {
		EmailDto emailDto = new EmailDto();
		emailDto.setReceivers(new String[] { "fangshuai0119@163.com" });
		emailDto.setCc(new String[] { "shuai.fang@mljr.com" });
		emailDto.setSubject("这是一个测试主题");
		emailDto.setCallerId(1L);

		User user1 = new User("fs1", 1);
		User user2 = new User("fs2", 2);
		List<User> userList = Lists.newArrayList(user1, user2);

		Map<String, Object> map = Maps.newHashMap();
		map.put("name", "fs");
		map.put("date", new Date());
		map.put("users", userList);

		emailDto.setContent(JSON.toJSONString(map));
		emailDto.setTemplateId(3L);

		sendMessage(JSON.toJSONString(emailDto));
	}

	public void sendMessage(String messageStr) {
		try {
			CloudQueue queue = client.getQueueRef("mail-test");
			Message message = new Message();
			message.setMessageBody(messageStr);
			Message putMsg = queue.putMessage(message);
			System.out.println("Send message id is: " + putMsg.getMessageId());
		} catch (ClientException ce)
		{
			System.out.println("Something wrong with the network connection between client and MNS service."
					+ "Please check your network and DNS availablity.");
			ce.printStackTrace();
		} catch (ServiceException se)
		{
			se.printStackTrace();
			if (se.getErrorCode() != null) {
				if (se.getErrorCode().equals("QueueNotExist"))
				{
					System.out.println("Queue is not exist.Please create before use");
				} else if (se.getErrorCode().equals("TimeExpired"))
				{
					System.out.println("The request is time expired. Please check your local machine timeclock");
				}
            /*
            you can get more MNS service error code from following link:
            https://help.aliyun.com/document_detail/mns/api_reference/error_code/error_code.html
            */
			}
		} catch (Exception e)
		{
			System.out.println("Unknown exception happened!");
			e.printStackTrace();
		}
	}

	@After
	public void after() {
		client.close();
	}

}